//
//  STRequest.m
//  OCUtil
//
//  Created by login on 15-6-17.
//
//

#import "STRequest.h"

#define BoundaryConstant @"1"

@implementation STRequest

+ (void)sendAsynchronousRequestWithUrlString:(NSString *)url
                                      params:(NSDictionary *)params
                                      method:(STRequestMethod)method
                           completionHandler:(STRequestCompletion)completionHandler
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    if (params) {
        NSMutableString *paramsStr = [NSMutableString stringWithCapacity:0];
        NSMutableArray *paramsArr = [NSMutableArray arrayWithCapacity:0];
        for (NSString *key in params) {
            id value = params[key];
            NSString *param = [NSString stringWithFormat:@"%@=%@", key, value];
            [paramsArr addObject:param];
        }
        [paramsStr appendString:[paramsArr componentsJoinedByString:@"&"]];
        
        if (method == STRequestMethodPost) {
            NSData *paramsData = [paramsStr dataUsingEncoding:NSUTF8StringEncoding];
            [request setHTTPBody:paramsData];
        }
        
        if (method == STRequestMethodGet) {
            if ([url rangeOfString:@"?"].location != NSNotFound) {
                url = [url stringByAppendingFormat:@"&%@", paramsStr];
            } else {
                url = [url stringByAppendingFormat:@"?%@", paramsStr];
            }
        }
    }
    
    url = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *req_url= [NSURL URLWithString:url];
    [request setURL:req_url];
    
    NSString *methodStr = [STRequest requestMethodName:method];
    [request setHTTPMethod:methodStr];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        if (completionHandler) {
            completionHandler(resultStr, info, connectionError);
        }
    }];
}

+ (NSDictionary *)sendSynchronousRequestWithUrlString:(NSString *)url
                                               params:(NSDictionary *)params
                                               method:(STRequestMethod)method;
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    if (params) {
        NSMutableString *paramsStr = [NSMutableString stringWithCapacity:0];
        NSMutableArray *paramsArr = [NSMutableArray arrayWithCapacity:0];
        for (NSString *key in params) {
            id value = params[key];
            NSString *param = [NSString stringWithFormat:@"%@=%@", key, value];
            [paramsArr addObject:param];
        }
        [paramsStr appendString:[paramsArr componentsJoinedByString:@"&"]];
        
        if (method == STRequestMethodPost) {
            NSData *paramsData = [paramsStr dataUsingEncoding:NSUTF8StringEncoding];
            [request setHTTPBody:paramsData];
        }
        
        if (method == STRequestMethodGet) {
            if ([url rangeOfString:@"?"].location != NSNotFound) {
                url = [url stringByAppendingFormat:@"&%@", paramsStr];
            } else {
                url = [url stringByAppendingFormat:@"?%@", paramsStr];
            }
        }
    }
    
    url = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [request setURL:[NSURL URLWithString:url]];
    
    NSString *methodStr = [STRequest requestMethodName:method];
    [request setHTTPMethod:methodStr];
    
    NSDictionary *retDict;
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    if (!error) {
        retDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"%@", error.localizedDescription);
        } else {
            return retDict;
        }
    } else {
        NSLog(@"%@", error.localizedDescription);
    }
    return nil;
}

+ (NSString *)requestMethodName:(STRequestMethod)method
{
    switch (method) {
        case STRequestMethodGet:
            return @"GET";
            break;
        case STRequestMethodPost:
            return @"POST";
        default:
            break;
    }
    return @"POST";
}

+ (void)uploadImageWithUrlString:(NSString *)url
                          params:(NSDictionary *)params
                           image:(UIImage *)image
                       imageName:(NSString *)imageName
               completionHandler:(STRequestCompletion)completionHandler
{
    // create request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    
    // set Content-Type in HTTP header
    NSString *boundary = @"_187934598797439873422234";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    // post body
    NSMutableData *body = [NSMutableData data];
    
    // add params (all params are strings)
    for (NSString *param in params) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", [params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    // add image data
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"picture\"; filename=\"%@\"\r\n", imageName] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    // setting the body of the post to the reqeust
    [request setHTTPBody:body];
    
    // set the content-length
    NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    
    // set URL
    [request setURL:[NSURL URLWithString:url]];
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", returnString);
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        if (completionHandler) {
            completionHandler(resultStr, info, connectionError);
        }
    }];
}

@end